<script setup lang="ts">
import { ref, toRefs, watch } from 'vue'
import useCategoryStore from '@/store/modules/category.ts'
import { reqDeleteSpu, reqSpuList } from '@/api/product/spu'
import { ElMessage } from 'element-plus'
import type { CategorySate } from '@/store/modules/types/type.ts'
import type { PagesData, ResponseData } from '@/api/type.ts'
import type { SPU } from '@/api/product/spu/type.ts'
import SpuForm from '@/views/product/spu/SpuForm.vue'
import SkuForm from '@/views/product/spu/SkuForm.vue'
import { reqSkuBySpuId } from '@/api/product/sku'
import { SKU } from '@/api/product/sku/type.ts'

const currentPage = ref<number>(1)
const limit = ref<number>(10)
const total = ref<number>(0)

const categoryStore = useCategoryStore()
const { c1Id, c2Id, c3Id } = toRefs<CategorySate>(categoryStore)

// 页面场景
const scene = ref<number>(0)
// 操作类型
enum OPERATION_TYPE {
  ADD = 'ADD',
  UPDATE = 'UPDATE',
  DELETE = 'DELETE',
}
let operate: string = ''

const spuRef = ref<any>()
const skuRef = ref<any>()

const spuList = ref<SPU[]>([])
const skuList = ref<SKU[]>([])
const showSkuList = ref<boolean>(false)

const getSpuList = async () => {
  try {
    const { code, data, message }: ResponseData<PagesData<SPU>> =
      await reqSpuList(currentPage.value, limit.value, c3Id.value as number)

    if (code === 200) {
      spuList.value = data?.records
      total.value = data?.total
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const onAddSpu = () => {
  operate = OPERATION_TYPE.ADD
  spuRef.value.initAddSpu(c3Id.value as number)
  scene.value = 1
}

const onAddSku = (row: SPU) => {
  scene.value = 2
  skuRef.value.initSku(c1Id.value, c2Id.value, c3Id.value, row)
}

const onEditSpu = (id: number) => {
  operate = OPERATION_TYPE.UPDATE
  scene.value = 1
  spuRef.value.initHasSpu(id)
}

const onShowSku = async (spuId: number) => {
  try {
    const { code, data, message } = await reqSkuBySpuId(spuId)
    if (code === 200) {
      skuList.value = data
      showSkuList.value = true
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const onDeleteSpu = async (id: number) => {
  try {
    const { code, data, message } = await reqDeleteSpu(id)
    if (code === 200) {
      ElMessage.success('删除成功')
      await getSpuList()
    } else {
      ElMessage.error(data ? data : message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const onPageSizeChange = () => {
  currentPage.value = 1
  getSpuList()
}

watch(
  () => c3Id.value,
  (newVal) => {
    // 重选c3后，前往第1页
    if (newVal) currentPage.value = 1
  },
)

watch(
  () => scene.value,
  (newVal) => {
    if (newVal == 0) {
      // 新增操作完成后回到第一页，其他操作留在当前页
      currentPage.value = operate == OPERATION_TYPE.ADD ? 1 : currentPage.value
      // spuRef.value.resetSpu()
      getSpuList()
    }
  },
)
</script>

<template>
  <div>
    <el-card>
      <Category @getDataList="getSpuList" :disabled="scene == 1" />
    </el-card>
    <el-card>
      <div v-show="scene == 0">
        <el-button
          type="primary"
          icon="plus"
          :disabled="!c3Id"
          @click="onAddSpu"
        >
          添加SPU
        </el-button>
        <el-table :data="spuList" border>
          <el-table-column
            prop="id"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column prop="spuName" label="SPU名称"></el-table-column>
          <el-table-column
            property="description"
            label="SPU描述"
          ></el-table-column>
          <el-table-column>
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                icon="Plus"
                title="添加SKU"
                @click="onAddSku(row)"
              ></el-button>
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                title="修改SPU"
                @click="onEditSpu(row?.id)"
              ></el-button>
              <el-button
                type="warning"
                size="small"
                icon="View"
                title="查看SKU"
                @click="onShowSku(row?.id)"
              />
              <el-popconfirm
                :title="`确认删除SPU：${row?.spuName}？`"
                confirm-button-text="确认"
                cancel-button-text="取消"
                width="200"
                @confirm="onDeleteSpu(row?.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                    title="删除SPU"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="limit"
          :page-sizes="[5, 10, 15, 20]"
          :total="total"
          :small="true"
          :background="true"
          layout="prev, pager, next, jumper, ->, total, sizes"
          @size-change="onPageSizeChange"
          @current-change="getSpuList"
        ></el-pagination>
      </div>
      <SpuForm v-show="scene == 1" v-model:scene="scene" ref="spuRef"></SpuForm>
      <SkuForm v-show="scene == 2" v-model:scene="scene" ref="skuRef"></SkuForm>
    </el-card>
    <el-dialog v-model="showSkuList" title="SKU列表">
      <el-table border :data="skuList">
        <el-table-column label="SKU名字" prop="skuName"></el-table-column>
        <el-table-column label="SKU价格" prop="price"></el-table-column>
        <el-table-column label="SKU重量" prop="weight"></el-table-column>
        <el-table-column label="SKU图片">
          <template #default="{ row }">
            <img :src="row.skuDefaultImg" style="width: 100px" alt="" />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>
